import React, {Component} from 'react';
import axios from 'axios';
import {Button, Table, Skeleton, Modal, Space, Input, message} from 'antd';

class AxiosPage extends Component {
  state = {
    list: [],
    columns: [
      {
        title: '编号',
        dataIndex: 'id',
        key: 'id'
      },
      {
        title: '姓名',
        dataIndex: 'name',
        key: 'name'
      },
      {
        title: '年龄',
        dataIndex: 'age',
        key: 'age'
      },
      {
        title: '操作',
        dataIndex: 'action',
        key: 'action',
        render: (text, record) => {
          return (
            <Space>
              <Button
                onClick={() =>
                  this.setState(
                    {
                      isShow: true,
                      isEdit: true,
                      modalTitle: '编辑',
                      isAdd: false,
                      record
                    })} type='primary'>编辑</Button>
              <Button
                onClick={() =>
                  this.setState(
                    {
                      isShow: true,
                      isEdit: false,
                      modalTitle: '警告',
                      record
                    })} type='danger'>删除</Button>
            </Space>
          )
        }
      }
    ],
    modalTitle: '提示',
    isShow: false,
    isEdit: true,
    record: {},
    isAdd: false
  };

  //1. 刚开始进入页面的时候 调用一次
  //2. 点击删除确定按钮的时候 调用一次
  //3. 编辑 点击确定按钮的时候 调用一次
  getAllList = () => {
    axios.get('/list').then(res => {
      console.log(res);
      let newList = res.data;
      newList = newList.reverse();
      newList.map(item => item['key'] = item['id']);
      this.setState({
        list: newList
      })
    });
  };

  componentDidMount() {
    this.getAllList();
  }

  modalOk = () => {
    let {isEdit, record, isAdd} = this.state;
    let {id, name, age} = record;
    if (isEdit) {

      if (isAdd) {
        //添加的逻辑
        axios({
          url: '/add',
          method: 'POST',
          data: {//post 请求 有一个 key 就是data  用来提交post请求的参数 data是一个对象
            name, age,
          }
        }).then(res => {
          message.success(res.data.message);
          this.getAllList();
        })
      } else {
        //编辑的逻辑
        //点击编辑的确定
        //请求接口
        // axios.post()
        axios({
          url: '/edit',
          data: {id, name, age},
          method: 'POST'
        }).then(res => {
          console.log(res.data);
          //1: 从服务器获取最新数据
          //2: message
          message.success(res.data.message);
          this.getAllList();
        }).catch(err => {
          message.error('编辑失败')

        });
      }
    } else {

      //点击删除的确定
      //获取的是id
      //把id传到后台
      console.log(record['id']);
      axios.post('/delete', {id: record['id']}).then(res => {
        message.success('删除成功');
        this.getAllList();
      }).catch(err => message.error('删除失败'));
    }

    this.setState({
      isShow: false
    })
  };

  render() {
    let {modalTitle, isShow, isEdit, record} = this.state;
    console.log(record);
    return (
      <div>
        <Button
          onClick={() => {
            //添加的逻辑
            //1. 弹框
            this.setState({
              isShow: true,
              isEdit: true,
              record: {},
              isAdd: true,
              modalTitle: '添加'
            })
          }} type='primary'>添加用户
        </Button>
        {
          this.state.list.length === 0 ?
            <Skeleton active/> :
            <Table columns={this.state.columns} dataSource={this.state.list}/>
        }


        <Modal
          title={modalTitle}
          visible={isShow}
          onOk={this.modalOk}
          onCancel={() => this.setState({isShow: false})}
        >
          {
            isEdit ? <Space>
              <Input value={record.name} onChange={(e) => {

                //this.setState 改变对象/数组中的值
                //三种方式
                //Object.assign
                //es6 中的语法 {...record, name: e.target.value},
                //record.name = e.target.value;

                /*Object.assign({},原始的对象,{添加的对象}) 合并对象*/
                record.name = e.target.value;
                this.setState({
                  // record: Object.assign({},record,{name: e.target.value})
                  // record: {...record, name: e.target.value}
                  record
                })
              }} placeholder='姓名'/>
              <Input value={record.age} onChange={(e) => {

                this.setState({
                  record: {...record, age: e.target.value}
                })

              }} placeholder='年龄'/>
            </Space> : <div>
              <h4>确定删除吗</h4>
            </div>
          }

        </Modal>
      </div>
    );
  }
}

export default AxiosPage;
